package com.yunchang.springboot.quatrz.scheduler;

import com.yunchang.springboot.mapper.base.BaseReportInfoMapper;
import com.yunchang.springboot.mapper.log.LogReportRecordMapper;
import com.yunchang.springboot.models.base.BaseReportInfo;
import com.yunchang.springboot.models.log.LogReportRecord;
import lombok.extern.slf4j.Slf4j;
import org.quartz.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.quartz.SchedulerFactoryBean;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;

import static org.quartz.JobBuilder.newJob;
import static org.quartz.TriggerBuilder.newTrigger;

@Slf4j
@Component
@EnableScheduling
public class MWSReportHistoryTestScheduler {
    @Value("${historyJobPath}")
    private String historyJobPath;

    /**
     * scheduler工厂bean，用于创建scheduler
     */
    @Autowired
    private SchedulerFactoryBean schedulerFactoryBean;

    /**
     * 基础报告信息
     */
    @Autowired
    private BaseReportInfoMapper baseReportInfoMapper;

    /**
     * 获取报告过程日志记录
     */
    @Autowired
    private LogReportRecordMapper logReportRecordMapper;


    public void schedulerTest() throws SchedulerException {
        log.info("开始mws历史拉取数据测试，时间：" + LocalDateTime.now().toString());
        BaseReportInfo baseReportInfo1 = baseReportInfoMapper.selectOneById(11);
        BaseReportInfo baseReportInfo2 = baseReportInfoMapper.selectOneById(12);
        BaseReportInfo baseReportInfo3 = baseReportInfoMapper.selectOneById(13);
        BaseReportInfo baseReportInfo4 = baseReportInfoMapper.selectOneById(14);
        BaseReportInfo baseReportInfo5 = baseReportInfoMapper.selectOneById(15);
        BaseReportInfo baseReportInfo6 = baseReportInfoMapper.selectOneById(6);
        BaseReportInfo baseReportInfo7 = baseReportInfoMapper.selectOneById(7);
        List<BaseReportInfo> list = new ArrayList<>();
        list.add(baseReportInfo1);
        list.add(baseReportInfo2);
        list.add(baseReportInfo3);
        list.add(baseReportInfo4);
        list.add(baseReportInfo5);
        list.add(baseReportInfo6);
        list.add(baseReportInfo7);
        Scheduler scheduler = schedulerFactoryBean.getScheduler();
        scheduler.start();
        for (BaseReportInfo baseReportInfo : list) {
            String name = baseReportInfo.getJobName();
//        String groupName = baseReportInfo.getJobGroup();
            String cronExpression = baseReportInfo.getHistoryCronExpression();
            String reportName = baseReportInfo.getChineseReportName();
            Class<? extends Job> jobClass = null;
            try {
                jobClass = (Class<? extends Job>) Class.forName(historyJobPath + baseReportInfo.getHistoryJobClass());
            } catch (ClassNotFoundException e) {
                // 获取报告日志记录对象
                LogReportRecord logReportRecord = new LogReportRecord();
                logReportRecord.setReportInfoId(baseReportInfo.getId());
                logReportRecord.setRemarks("job类不存在!");
                logReportRecord.setAddTime(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss").format(LocalDateTime.now()));
                logReportRecord.setModTime(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss").format(LocalDateTime.now()));
                logReportRecordMapper.insertSelective(logReportRecord);
            }
            // 创建对应的job类
            JobDetail job = newJob(jobClass)
                    .withIdentity(name, "history")
                    .usingJobData("reportName", reportName)
                    .usingJobData("reportType", baseReportInfo.getReportType())
                    .usingJobData("timeScope", baseReportInfo.getReportTimeScope())
                    .usingJobData("getReportArea", baseReportInfo.getGetReportArea())
                    .usingJobData("reportInfoId", baseReportInfo.getId())
                    .usingJobData("getHistoryTime", baseReportInfo.getGetHistoryTime())
                    .build();
            // 根据cron表达式创建触发器
            Trigger trigger = newTrigger()
                    .withIdentity(name, "history")
                    .withSchedule(CronScheduleBuilder.cronSchedule(cronExpression).withMisfireHandlingInstructionFireAndProceed())
                    .build();
            // 将job和触发器作为参数启动scheduler
            scheduler.scheduleJob(job, trigger);
        }
    }
}
